package com.hy.lightning.commons.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;

public class JSON<K,V> {
	
	public static final ObjectMapper objectMapper = new ObjectMapper();
	
	static {
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		//设置有属性不能映射成PO时不报错  
		objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
		
		/**
		 * 当值为null是序列化为""
		 */
		objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {

			@Override
			public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
					throws IOException, JsonProcessingException {
				jgen.writeString("");
			}
		});
	}
	
	public static String toString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
		return objectMapper.writeValueAsString(object);
	}
	
	public static <T> Object toObj(String jsonStr, Class<T> c) throws JsonParseException, JsonMappingException, IOException {
		return objectMapper.readValue(jsonStr, c);
	}
	
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		Map<String,String> map = new HashMap<>();
		map.put("name", "hy");
		System.out.println(toString(map));
	}
	
	private Map<K,V> map = new HashMap<>();
	
	public JSON<K,V> put(K k, V v) {
		map.put(k, v);
		return this;
	}
	
	@Override
	public String toString() {
		try {
			return objectMapper.writeValueAsString(map);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public Map<K,V> toMap(String jsonStr) throws JsonParseException, JsonMappingException, IOException {
		return (Map<K, V>) objectMapper.readValue(jsonStr, Map.class);
	}
}
